import Taro, { Component } from '@tarojs/taro'
import { View, Image, ScrollView, Swiper, SwiperItem } from '@tarojs/components'
import { connect } from '@tarojs/redux'

import { usered, user } from '../../../actions/counter'
import allExtrance from '../../../config/allExtrance';
import allRequest from './../../../api/allRequest'
import { ConsumerMenu, Tabbar, ConsumerJobList, Footer, SignIn, GetUserInfo } from './../../../component/index'
import wechat from './../../../config/weixinJssdk'
import config from './../../../config/domian'
import './index.less'


let _this

@connect(({ counter }) => ({
  counter
}), (dispatch) => ({
  usered() {
    dispatch(usered())
  },
  user() {
    dispatch(user())
  },
}))
class Index extends Component {

  config = {
    navigationStyle: "custom",
    navigationBarTitleText: '首页',
    disableScroll: true,
    onReachBottomDistance: 1,
    // enablePullDownRefresh: true,
  }

  constructor() {
    super();
    this.state = {
      searchItem: {
        latitude: '',
        longitude: '',
        order: 'default',
        position_id: '',
        area_id: '',
        keyword: '',
        worker_demand_id: ''
      },
      slideImgUrls: [],
      swiperCurrent: 0,
      page: 0,
      jobList: [],
      showFooter: false,
      loading: false,   //是否正在加载中
      headerType: 'big',  //头部样式
      scrollTop: 0,
      shareImg: '',
      customImageInfo: {},
      showWechat: false,
      custimer_config: {}
    }
  }

  onShareAppMessage() {
    let { shareImg, customImageInfo } = this.state
    // task.invite(this.state.companyJobId).catch(err => { console.log(err) })
    return {
      title: customImageInfo.title || `推荐${Taro.getStorageSync('name')}，快速找到好工作！`,
      path: '/pages/loading/loading?debug=debug',
      imageUrl: customImageInfo.weapp_img || shareImg || 'https://file.open.banchengyun.com/2019/05/21/155842392564187.jpg'
    }
  }


  componentWillReceiveProps(nextProps) {
    console.log(this.props, nextProps)
  }

  componentDidMount() {
    _this = this
    //缓存用户处于用户端
    Taro.setStorageSync('situation', 'consumer')
    // 获取版本信息及用户信息
    this.getData()
    // this.getLocation()
    //获取联系客服相关信息
    this.getWechat()

  }

  componentWillUnmount() { }

  componentDidShow() {
    if (Taro.getStorageSync("consumerIndexBanner") != '') {
      this.setState({
        slideImgUrls: JSON.parse(Taro.getStorageSync("consumerIndexBanner"))
      })
    }
    this.getTranmistPoster()

  }

  componentDidHide() { }

  //获取首页转发卡片海报
  getTranmistPoster() {
    allRequest.indexTranmistPoster().then((result) => {
      let { defayltImageUrl, customImageInfo } = result.data
      this.setState({
        shareImg: defayltImageUrl,
        customImageInfo
      }, () => {
        if (Taro.getEnv() === Taro.ENV_TYPE.WEB) {
          wechat.config()
          let obj = {
            title: customImageInfo.title || `推荐${Taro.getStorageSync('name')}，快速找到好工作！`, // 分享标题
            desc: customImageInfo.h5_content || '', // 分享描述
            link: `${config[process.env.NODE_ENV].hostSaas}/#/pages/consumer/index/index?debug=debug`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: customImageInfo.h5_icon || 'https://file.open.banchengyun.com/2019/05/21/155842392564187.jpg', // 分享图标
            success: () => {
              // 设置成功
              console.log("H5分享设置成功")
            }
          };
          wechat.share(obj)
        }
      })
    }).catch((err) => {
      console.log(err)
    });
  }

  //处理查询条件
  dealSearchItem(item) {
    let { searchItem } = _this.state
    if (item.order && item.order == 'distance' && searchItem.latitude == '' && searchItem.longitude == '') {
      _this.getLocation()
      return
    }
    for (let i in item) {
      searchItem[i] = item[i]
    }
    _this.setState({
      searchItem,
      page: 0,
      jobList: [],
      showFooter: false,
    }, () => {
      _this.getData()
    })
  }

  refresh() {
    _this.setState({
      searchItem: {},
      page: 0,
      jobList: [],
      showFooter: false,
    }, () => {
      _this.getData()
    })
  }

  getData() {
    let { searchItem, page, jobList, showFooter } = _this.state
    _this.setState({ loading: true })
    !showFooter && Taro.showLoading({ title: '加载中' })
    //获取推荐职位
    let recomandJobs = Taro.getStorageSync('recomandJobs')
    if (recomandJobs) {
      _this.setState({ recomandJobs: JSON.parse(recomandJobs) })
    }
    let promise = new Promise((resolve, reject) => {
      allRequest.job({ ...searchItem, page: ++page }).then((result) => {
        if (result.data.length) {
          let arr = []
          for (let i = 0; i < result.data.length; i++) {
            if (Taro.getStorageSync('location')) {
              let location = JSON.parse(Taro.getStorageSync('location'))
              result.data[i].distanceStr = _this.getDistance(location.latitude, location.longitude, result.data[i].company.latitude, result.data[i].company.longitude)
            }
            arr.push(result.data[i])

          }
          _this.setState({
            jobList: [...jobList, ...arr],
            page: page
          }, () => {
            if (result.data.length < 5) {
              _this.setState({ showFooter: true }, () => { Taro.hideLoading() })
            } else {
              Taro.hideLoading()
            }
          })
          // 缓存推荐职位，首选默认第一页职位数据
          if (page == 1 && searchItem.order == 'default' && searchItem.position_id == '' && searchItem.area_id == '') {
            allExtrance.util.Taro.setStorageSync("recomandJobs", result.data)
          }
          resolve(true)
        } else {
          if (page > 1) {
            _this.setState({ showFooter: true }, () => { Taro.hideLoading(); console.log(_this.state.showFooter) })
          } else {

            _this.setState({ showFooter: false }, () => { Taro.hideLoading() })
          }
          resolve(_this)
        }
      }).catch(err => {
        reject(err)
      })
    })
    promise.then((result) => {
      if (result) {
        _this.setState({ loading: false })
      }
    }).catch(err => {
      allExtrance.util.Taro.showToast(err)
    })
  }



  scrolltolower(e) {
    let { jobList, showFooter, loading } = this.state
    // 空数据无上划加载
    if (jobList.length == 0 && !showFooter && !loading) {
      return
    }
    this.getData();
  }

  listenScroll(e) {
    this.setState({ scrollTop: e.target.scrollTop })
    if (e.target.scrollTop > 50) {
      this.setState({ headerType: 'small' })
    }
  }

  listenTopUpper(e) {
    this.setState({ headerType: 'big' })
  }

  changeHeaderType(e) {
    if (e == 'big' && _this.state.scrollTop > 100) {
      return
    }
    _this.setState({ headerType: e })
  }

  getLocation() {
    const isWx = Taro.getEnv() === Taro.ENV_TYPE.WEAPP
    const isH5 = Taro.getEnv() === Taro.ENV_TYPE.WEB
    if (isWx) {
      Taro.getSetting().then((res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {//非初始化进入该页面,且未授权
          Taro.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
            success: (result) => {
              if (result.cancel) {
                // 已拒绝授权
              } else if (result.confirm) {
                Taro.openSetting().then((data) => {
                  if (data.authSetting["scope.userLocation"] == true) {
                    allExtrance.util.Taro.showToast('授权成功')
                    //再次授权，调用getLocationt的API
                    this.latLong().then((msg) => {
                      let { searchItem } = this.state
                      let location = {
                        latitude: msg.latitude,
                        longitude: msg.longitude
                      }
                      searchItem.latitude = msg.latitude
                      searchItem.longitude = msg.longitude
                      Taro.setStorageSync("location", JSON.stringify(location))
                      this.setState({
                        searchItem
                      }, () => {
                        this.dealSearchItem({ order: 'distance' })
                      })
                    })
                  } else {
                    allExtrance.util.Taro.showToast('您已拒绝授权')
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == true || typeof res.authSetting['scope.userLocation'] == 'undefined') {//初始化进入
          this.latLong().then((data) => {
            let { searchItem } = this.state
            let location = {
              latitude: data.latitude,
              longitude: data.longitude
            }
            searchItem.latitude = data.latitude
            searchItem.longitude = data.longitude
            Taro.setStorageSync("location", JSON.stringify(location))
            this.setState({
              searchItem
            }, () => {
              this.dealSearchItem({ order: 'distance' })
            })

          }).catch((err) => {
            console.log(err)
            this.getLocation()
          });
        }
      })
    } else if (isH5) {
      Taro.showModal({
        title: '地理信息授权',
        content: '获取地址需要您的授权，是否为您唤起地理信息授权？',
      })
        .then(res => {
          if (res.confirm) {
            const geolocation = new qq.maps.Geolocation("JLJBZ-T5ZL2-BELUZ-C6DNP-HU4M5-SJBAG", "myapp");
            const options = { timeout: 8000 };
            geolocation.getLocation(this.showPosition, this.showErr, options);
          }
          if (res.cancel) {
          }
        })

    }

  }
  showPosition(position) {
    let { lat, lng } = position
    let { searchItem } = _this.state
    let location = {
      latitude: lat,
      longitude: lng
    }
    searchItem.latitude = lat
    searchItem.longitude = lng
    Taro.setStorageSync("location", JSON.stringify(location))
    _this.setState({
      searchItem
    }, () => {
      _this.dealSearchItem({ order: 'distance' })
    })
  };

  showErr() {
    console.log('H5定位失败')
  };
  latLong() {
    return new Promise((resolve, reject) => {
      Taro.getLocation({ type: 'wgs84' }).then((result) => {
        resolve(result)
      }).catch((err) => {
        reject(false)
      })
    })
  }

  toSearch(e) {
    Taro.navigateTo({
      url: `/subPackages/subPackageS/search/search`
    })
  }
  Rad(d) { //根据经纬度判断距离
    return d * Math.PI / 180.0;
  }
  getDistance(lat1, lng1, lat2, lng2) {
    // lat1用户的纬度
    // lng1用户的经度
    // lat2企业的纬度
    // lng2企业的经度
    let radLat1 = this.Rad(lat1);
    let radLat2 = this.Rad(lat2);
    let a = radLat1 - radLat2;
    let b = this.Rad(lng1) - this.Rad(lng2);
    let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;
    s = Math.round(s * 10000) / 10000;
    s = s.toFixed(2) + 'km' //保留两位小数
    console.log('经纬度计算的距离:' + s)
    return s
  }

  hasWechatUser() {
    _this.props.user()
  }

  swiperChange(e) {
    this.setState({
      swiperCurrent: e.detail.current
    })
  }

  advertizeTo(list, e) {
    let url = ''
    switch (list.skip_type) {
      case "job":
        url = `/subPackages/subPackageS/jobInfo/jobInfo?companyJobId=${list.skip_id}`
        break;
      case "company":
        url = `/subPackages/subPackageS/brandInfo/brandInfo?company_id=${list.skip_id}`
        break;
      case "topic":
        if (list.topice_type == 'job') {
          url = `/subPackages/subPackageS/portSubject/portSubject?topice_id=${list.skip_id}`
        } else if (list.topice_type == 'company') {
          url = `/subPackages/subPackageS/firmSubject/firmSubject?topice_id=${list.skip_id}`
        }
        break;
      case "resume":
        url = `/subPackages/subPackageS/myResume/myResume`
        break;
      default:
        break;
    }
    Taro.navigateTo({
      url
    })
  }

  getWechat() {
    allRequest.customerConfig().then((result) => {
      let { custimer_config } = result
      custimer_config = JSON.parse(custimer_config)
      this.setState({ custimer_config })
    }).catch((err) => {
      console.log(err)
    });
  }



  render() {
    const currentPage = 'consumerResume'
    const WEB = (Taro.getEnv() === Taro.ENV_TYPE.WEB ? true : false)
    const WEAPP = (Taro.getEnv() === Taro.ENV_TYPE.WEAPP ? true : false)
    let { jobList, showFooter, recomandJobs, loading, slideImgUrls, swiperCurrent, headerType,
      showWechat, custimer_config } = this.state
    return (
      <View className='consumerIndex' style={`overflow:hidden;${Taro.getEnv() === Taro.ENV_TYPE.WEB ? '' : 'height:100vh;'}`}>
        {
          headerType == 'big' && <View className='headerTwo'>
            <View className='header' style={`height: ${Taro.getStorageSync("consumerIndexBanner") == '' ? '151px' : '175px;'};background-color:${Taro.getStorageSync('baseColor')}`}>
              <View className='logoBlock'>
                <Image className='logo' src={Taro.getStorageSync("logo")}></Image>
              </View>
              <View className='searchBlock'>
                <View className='search' onClick={this.toSearch.bind(this)}>
                  <Image className='searchImg' src='https://file.open.banchengyun.com/2019/04/01/155410697752500.png'></Image>
                  <View className='content'>搜索企业/职位</View>
                </View>
              </View>
            </View>
            {
              Taro.getStorageSync("consumerIndexBanner") != '' && <View className='advertize'>
                <Swiper autoplay='true' interval='2000' duration='500' circular current={swiperCurrent} onChange={this.swiperChange.bind(this)} style='height:100%;'>
                  {
                    slideImgUrls.length && slideImgUrls.map((item, index) =>
                      <SwiperItem>
                        <Image src={item.image_url} mode='aspectFill' class='slideImage' onClick={this.advertizeTo.bind(this, item)} />
                      </SwiperItem>
                    )
                  }
                </Swiper>
                <View className='dots'>
                  {
                    slideImgUrls.length > 1 && slideImgUrls.map((item, index) =>
                      <View class={`dot ${index == swiperCurrent ? 'active' : ''}`} style={`${index == swiperCurrent && ('background:' + Taro.getStorageSync('baseColor'))}`}></View>
                    )
                  }
                </View>
              </View>
            }

          </View>
        }
        {
          headerType == 'small' && <View className='headertop' style={`background:${Taro.getStorageSync('baseColor')}`}>
            <View className='logoSearch'>
              <Image className='logoImg' src={Taro.getStorageSync("logo")}></Image>
              <View className='headerBlock' onClick={this.toSearch.bind(this)}>
                <Image className='searchImg' src='https://file.open.banchengyun.com/2019/04/01/155410697752500.png'></Image>
                <View className='content'>搜索企业/职位</View>
              </View>
            </View>
          </View>
        }

        <View className='menuBlock'>
          <ConsumerMenu onDealRefresh={this.dealSearchItem} onheaderType={this.changeHeaderType}></ConsumerMenu>
        </View>
        <ScrollView className='jobList' style={`${(WEAPP ? (headerType == 'big' && Taro.getStorageSync("consumerIndexBanner") != '' ? 'height:27rem' : 'height:41rem') : (headerType == 'big' && Taro.getStorageSync("consumerIndexBanner") != '' ? 'height:16rem' : 'height:24rem'))}`} scrollY enableBackToTop='true' onScrollToLower={this.scrolltolower.bind(this)} onScroll={this.listenScroll.bind(this)} onScrollToUpper={this.listenTopUpper.bind(this)}>
          {jobList.length > 0 && <View className='jobBlock' style={`${Taro.getEnv() === Taro.ENV_TYPE.WEB ? 'max-height: 60vh;' : ''}`}>
            <ConsumerJobList jobs={jobList} type=''></ConsumerJobList>
            {showFooter && <View className='footerBlock'><Footer></Footer></View>}
          </View>}
          {jobList.length == 0 && !showFooter && !loading && <View className='recomand'>
            <View className='empty-result-box'>
              <Image className='emptyImg' src='https://file.open.banchengyun.com/353/b523b8edfce42fde63a6ba09d12e073c' ></Image>
              <View className='text'>没有匹配的职位，修改搜索条件再试试~</View>
            </View>
            <View className='recommandBlock'>
              <View className='recommand'>·其他优质岗位·</View>
            </View>
            <ConsumerJobList jobs={recomandJobs}></ConsumerJobList>
            <Footer></Footer>
          </View>}
        </ScrollView>
        {/* <View className='getlocation' onClick={this.getLocation}>
          <Btn title='获取授权'></Btn>
        </View> */}
        {/* <View style='width:100%;height:48px'></View> */}
        <Tabbar currentPage={currentPage}></Tabbar>
        {this.props.counter && (this.props.counter.signStatus && <SignIn onRefresh={this.refresh}></SignIn>)}
        {this.props.counter && (this.props.counter.hasUser && <GetUserInfo onHasWechatUser={this.hasWechatUser} url='/pages/consumer/index/index'></GetUserInfo>)}
        {/* <!-- 联系客服图标 --> */}
        <View onClick={() => { this.setState({ showWechat: true }) }}>
          <Image className='icon-index' src='https://file.open.banchengyun.com/353/c2b51a3c1c1f0112353486593108f4f8' />
        </View>
        {
          showWechat && <View className='zhezhao' onClick={() => { this.setState({ showWechat: false }) }}>
            <View className='messageBlock'>
              <View className='themeColor' style={`background-color:${Taro.getStorageSync('baseColor')}`}>
                <View className='logoImg'>
                  <Image src='https://file.open.banchengyun.com/2019/06/25/156145661067994.png'></Image>
                </View>
                <View className='cloud'>
                  <Image src='https://file.open.banchengyun.com/2019/06/25/156145781925397.png' />
                </View>
              </View>
              <View className='msgContent'>
                <View className='msgTitle'>{custimer_config.text}</View>
                <Image src={custimer_config.img} className='msgImg'></Image>
              </View>
              <View className='msgClose' onClick={() => { this.setState({ showWechat: false }) }}>
                <Image src='https://file.open.banchengyun.com/2019/06/25/156145781914338.png'></Image>
              </View>
            </View>
          </View>
        }

      </View>
    )
  }
}

export default Index